package com.hougong.im.utils;

import com.alibaba.fastjson.JSON;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {
    /** 时间格式(yyyy-MM-dd) */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /** 时间格式(yyyy-MM-dd HH:mm:ss) */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static String format(Date date) {
        return format(date, DATE_PATTERN);
    }

    public static String format(Date date, String pattern) {
        if(date != null){
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }
    public static Date parseDate(String date,String pattern) throws ParseException {
        if(date!=null){
            SimpleDateFormat df=new SimpleDateFormat(pattern);
            return df.parse(date);
        }else {
            throw new NullPointerException("时间字符串 为空!");
        }
    }


    /**
     * 返回聊天记录的时间格式字符串
     * @param date
     * @return
     */
    public static String formatChatTime(Date date){
        String  dateStr=format(date,DATE_TIME_PATTERN);
        String year = dateStr.substring(0,4);
        Long yearNum =Long.parseLong(year);
        int month = Integer.parseInt(dateStr.substring(5,7));
        int day = Integer.parseInt(dateStr.substring(8,10));
        String hour = dateStr.substring(11,13);
        String minute = dateStr.substring(14,16);

        long addtime =date.getTime();
        long today = System.currentTimeMillis();//当前时间的毫秒数
        Date now = new Date(today);
        String  nowStr=format(now,DATE_TIME_PATTERN);
        int  nowDay = Integer.parseInt(nowStr.substring(8,10));
        String result="";
        long l=today-addtime;//当前时间与给定时间差的毫秒数
        long days=l/(24*60*60*1000);//这个时间相差的天数整数，大于1天为前天的时间了，小于24小时则为昨天和今天的时间
        long hours=(l/(60*60*1000)-days*24);//这个时间相差的减去天数的小时数
        long min=((l/(60*1000))-days*24*60-hours*60);//
        long s=(l/1000-days*24*60*60-hours*60*60-min*60);
        if(days > 0){
            if(days>0 && days<2){
                result ="前天"+hour+":"+minute;
            } else {
                result = yearNum+"-"+month+"- "+day+" "+hour+":"+minute;
            }
        }else if(hours > 0 ) {
            if(day!=nowDay){
                result = "昨天"+hour+":"+minute;
            }else{
                result=hours+"小时前";
            }
        } else if(min > 0){
            if(min>0 && min<15){
                result="刚刚";
            } else {
                result=min+"分前";
            }
        }else {
            result=s+"秒前";
        }
        return result;
    }

    public static void main(String[] args) {
        String s = formatChatTime(new Date(1537025284403L));
        System.out.println(s);
        Date date=new Date();
        System.out.println(JSON.toJSONString(date));
    }
}
